import JSZip from 'jszip'

function downloadData(data, filename) {
  const link = document.createElement('a')
  document.body.appendChild(link)
  link.href = URL.createObjectURL(data)
  link.download = filename
  link.click()

  setTimeout(() => {
    document.body.removeChild(link)
  }, 1000)
}

/**
 * 处理生成的注释，大小不能自适应的问题
 * 参考: https://github.com/exceljs/exceljs/pull/1933
 * TODO 对此问题，应当关注上方提到的 PR，若其被合并，应当更新引用版本。到那时，就不再需要通过此方法处理了
 * 最终，样式在写进了文件 xl/drawings/vmlDrawing2.vml
 * 替换其中的 <v:textbox style="mso-direction-alt:auto" 字样为:
 * <v:textbox style="mso-direction-alt:auto;mso-fit-shape-to-text:t"
 * @param {ArrayBuffer} buffer
 * @return {Promise<ArrayBuffer>}
 */
async function fixCommentStyle(buffer) {
  const zip = await JSZip.loadAsync(buffer)
  const vmlDrawing2FileName = 'xl/drawings/vmlDrawing2.vml'
  // Get the style file
  const vmlDrawing2 = zip.file(vmlDrawing2FileName)
  if (!vmlDrawing2) {
    // eslint-disable-next-line
    console.warn(`Cannot find ${vmlDrawing2FileName}`)
    return buffer
  }
  // Get content as string
  const xml = await vmlDrawing2.async('string')

  const placeholder = '<v:textbox style="mso-direction-alt:auto;mso-fit-shape-to-text:t"'
  const newXml = xml.replace(/<v:textbox style="mso-direction-alt:auto"/g, placeholder)
  // Write back to the file
  zip.file(vmlDrawing2FileName, newXml)
  return await zip.generateAsync({type: 'arraybuffer'})
}

export default {
  downloadData,
  fixCommentStyle
}
